/**
 * @description promise.all 实现
 * @param   {Array}  promises promise数组
 * @returns {Object} Promise对象
 */
const promiseAll = (promises) => {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promises)) {
      reject("参数必须是数组");
    }
    let count = 0; // 用来记录异步函数的完成个数
    let resolved = []; // 最终返回的数组
    const length = promises.length; // 参数的长度
    for (let i = 0; i < length; i++) {
      const promise = promises[i];
      if (promise.then && typeof promise.then === "function") {
        // promise 对象
        promise
          .then((res) => {
            count++;
            resolved[i] = res; // 返回值按下标值插入到数组中
            if (count === length) {
              // 异步函数已经全部执行完毕
              resolve(resolved);
            }
          })
          .catch((err) => {
            reject(err);
          });
      } else {
        // 非promise对象
        count++;
        resolved[i] = promise;
      }
    }
  });
};

// 测试
const sleep = (seconds) =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(seconds);
    }, seconds);
  });
promiseAll([sleep(3000), 123, sleep(1000)]).then((res) => {
  console.log("res :>> ", res);
});
